﻿using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.HttpResults;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Net;
using System.Security.Claims;
using System.Text;

namespace WebApplication1.WebApi.Controllers {
    [Route("api/[controller]")]
    [ApiController]
    public class AuthController : ControllerBase {
        private readonly IConfiguration _configuration;

        public AuthController(IConfiguration configuration) {
            _configuration = configuration;
        }
        [HttpPost]
        public async Task<IActionResult> Authenticate([FromBody] Credential credential) {
            //Verify the credential
            if(credential.UserName == "admin" && credential.Password == "123456") {
                //Creating the security context
                var claims = new List<Claim>() {
                    new Claim(ClaimTypes.Name,"admin"),
                    new Claim(ClaimTypes.Email,"example@mywebsite.com"),
                    new Claim("Admin","true"),
                    new Claim("EmploymentDate","2020-01-01")
                };

                var expiresAt = DateTime.UtcNow.AddMinutes(7);
                var jwtObj = new {
                    access_token = generateJwtToken(claims, expiresAt),
                    expires_at = expiresAt,
                };
                return Ok(jwtObj);
            } else {
                ModelState.AddModelError("Unauthorized", "该用户权限不够");
                return Unauthorized(ModelState);
            }
        }

        private string generateJwtToken(IEnumerable<Claim> claims, DateTime expiresAt) {
            byte[] secretkey = Encoding.ASCII.GetBytes(_configuration.GetValue<string>("SecretKey") ?? "");
            JwtSecurityToken jwtToken = new JwtSecurityToken(
                claims: claims,
                notBefore: DateTime.UtcNow,
                expires: expiresAt,
                signingCredentials: new Microsoft.IdentityModel.Tokens.SigningCredentials(
                    new SymmetricSecurityKey(secretkey),
                    SecurityAlgorithms.HmacSha256Signature)
                );
            return new JwtSecurityTokenHandler().WriteToken(jwtToken);
        }
    }

    public class Credential {

        public string UserName { get; set; } = string.Empty;

        public string Password { get; set; } = string.Empty;

        public bool RememberMe { get; set; } = false;
    }
}
